package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应对象
 */
public class HttpRseponse {
    //状态行相关信息
    private int statusCode = 200;
    private String statusReason = "ok";

    //响应头相关信息
    private Map<String,String> headers = new HashMap<>();
    //响应正文相关信息
    private File entity;//正文对应的实体文件
    private Socket socket;


    public HttpRseponse(Socket socket){
        this.socket = socket;
    }


    /**
     * 将响应发送给客户端
     */
    public void flush() throws IOException {
        //1发送状态行
        sendStatusLine();
        //2发送响应头
        sendHeaders();
        //3发送响应正文
        sendContent();
    }
    private void sendStatusLine() throws IOException {
        OutputStream out = socket.getOutputStream();
        String line = "HTTP/1.1 "+statusCode+" "+statusReason;
        byte[] data = line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);//写回车符
        out.write(10);//写换行符
    }
    private void sendHeaders() throws IOException {
        OutputStream out = socket.getOutputStream();

        for(Map.Entry<String,String> entry : headers.entrySet()){
            String line = entry.getKey()+": "+entry.getValue();
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);//写回车符
            out.write(10);//写换行符
        }




        //单独发送CRLF表示响应头发送完毕
        out.write(13);//写回车符
        out.write(10);//写换行符
    }
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        try(
            FileInputStream fis = new FileInputStream(entity);
        ) {
            byte[] data = new byte[1024 * 10];//10kb
            int len;
            while ((len = fis.read(data)) != -1) {
                //写出在data数组中从0-len长度的字节,可能每次都是满的但是最后一次是不满的就不会给10kb长度的字节
                out.write(data, 0, len);
            }
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
    }
    public void setHeader(String name, String value){
        headers.put(name,value);
    }
}
